package com.wfm.lock;

import java.util.concurrent.locks.StampedLock;

public class StampedLockStateChangeExample {
    public static void main(String[] args) {
        StampedLock stampedLock = new StampedLock();

        // 初始情况
        System.out.println("初始状态：没有获取任何锁");

        // 乐观读操作
        long optimisticStamp = stampedLock.tryOptimisticRead();
        System.out.println("乐观读戳记: " + Long.toBinaryString(optimisticStamp));

        // 验证乐观读，这里假设没有其他线程进行写操作
        boolean isValid = stampedLock.validate(optimisticStamp);
        System.out.println("乐观读验证结果: " + isValid);

        // 获取读锁
        long readStamp = stampedLock.readLock();
        System.out.println("读锁戳记: " + Long.toBinaryString(readStamp));

        // 释放读锁
        stampedLock.unlockRead(readStamp);
        System.out.println("读锁已释放");

        // 获取写锁
        long writeStamp = stampedLock.writeLock();
        System.out.println("写锁戳记: " + Long.toBinaryString(writeStamp));

        // 释放写锁
        stampedLock.unlockWrite(writeStamp);
        System.out.println("写锁已释放");
    }
}